import '../../../../tenant/dialog/css/relate.css';

/**
 * 租户管理
 */
define(function (require, exports, module) {
    var angular = require('angular');
    var ui = require('@yunke/core/ui');
    var util = require('@yunke/core/util').default;
    var $ = window.$ = window.jQuery = require('jquery');
    require("@yunke/jquery_pagination");
    require("angular-messages");
    require("@yunke/core/angular_public_interceptor");
    require('angular-ui');
    require('./../contract/contract-common');
    require("highcharts");
    require('./yk_tree');
    require("@yunke/angular-ui/lib/clipboard");
    var _ = require('lodash');
    var moment = require('moment');

    const tenantType = [
        {
            text: '正式',
            value: '0'
        },
        {
            text: '测试',
            value: '1'
        }
    ];

    const tenantStatus = [
        {
            text: '启用',
            value: '1'
        },
        {
            text: '禁用',
            value: '0'
        }
    ];

    angular.module('Tenant', ['angularPublicInterceptor', 'ngMessages', 'ngUI', 'ContractCommonService', 'ykTree', 'angular.directive.clipboard'])
        .constant('searchErpFields', [{
            value: '0',
            name: '全部'
        }, {
            value: '1',
            name: '正常'
        }, {
            value: '2',
            name: '即将过期'
        }, {
            value: '3',
            name: '已过期'
        }, {
            value: '4',
            name: '已禁用'
        }])
        .filter('authorizeStatus', ['searchErpFields', function (searchErpFields) {
            return function (origin) {
                if (!origin) {
                    return '';
                }
                return searchErpFields[origin].name;
            }
        }])
        .directive('ykMoreThan', function () {
            return {
                restrict: "A",
                require: "ngModel",
                scope: {
                    ykMoreThan: '&'
                },
                link: function (scope, ele, attrs, ctrl) {
                    scope.$parent.$watch(scope.ykMoreThan, function (newValue, oldValue) {
                        if (newValue !== oldValue) {
                            ctrl.$parsers.shift();
                            ctrl.$parsers.push(function (viewValue) {
                                ctrl.$setValidity('morethan', viewValue >= scope.$eval(scope.ykMoreThan));
                                return viewValue;
                            });
                        }
                    });
                }
            }
        })
        .service('orgs', ['$http', '$q', function ($http, $q) {
            /**
             * 租户列表
             */
            return function (params) {
                var deferred = $q.defer();

                $http.get('/orgapi/index.php?r=mtp/myscrm-organization/get-orgs', {params: params})
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('contracts', ['$http', '$q', function ($http, $q) {
            /**
             * 合同列表
             */
            return function (params) {
                var deferred = $q.defer();

                $http.get('/orgapi/index.php?r=mtp/myscrm-organization/get-contracts-list', {params: params})
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('cancelContract', ['$http', '$q', function ($http, $q) {
            /**
             * 作废合同
             */
            return function (params) {
                var deferred = $q.defer();

                $http.post('/orgapi/index.php?r=mtp/myscrm-organization/cancel-contract', params)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('updateDeliver', ['$http', '$q', function ($http, $q) {
            /**
             * 更新租户交付信息
             */
            return function (params) {
                var deferred = $q.defer();

                $http.post('/orgapi/index.php?r=mtp/myscrm-organization/update-deliver-info', params)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('editContract', ['$http', '$q', function ($http, $q) {
            /**
             * 新增或更改合同
             */
            return function (params) {
                var deferred = $q.defer();

                $http.post('/orgapi/index.php?r=mtp/myscrm-organization/save-contract', params)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('allPackages', ['$http', '$q', function ($http, $q) {
            /**
             * 所有的包信息
             */
            return function (params, search) {
                var deferred = $q.defer();

                $http.get('/orgapi/index.php?r=mtp/myscrm-organization/get-main-product-applications' + (search || ''), params)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('packagesByOrg', ['$http', '$q', function ($http, $q) {
            /**
             * 所有的包信息
             */
            return function (params) {
                var deferred = $q.defer();

                $http.post('/orgapi/index.php?r=mtp/myscrm-organization/get-packages-by-org', params)
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            };
        }])
        .service('contractRenewal', ['$http', '$q', function ($http, $q) {
            /**
             * 续租下获取合同签约应用信息
             */
            return function (params) {
                var deferred = $q.defer();

                $http.get('/orgapi/index.php?r=mtp/myscrm-organization/get-need-renewed-projects', {params: params})
                    .success(function (res) {

                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            }
        }])
        .service('getContractNum', ['$http', '$q', function ($http, $q) {
            /**
             * 获取续签合同列表
             */
            return function (params) {
                var deferred = $q.defer();
                $http.get('/orgapi/index.php?r=mtp/myscrm-organization/get-overdue-or30days-overdue-contracts', {params: params})
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });

                return deferred.promise;
            }

        }])
        .service('getRenewalApplication', ['$http', '$q', function ($http, $q) {
            /**
             * 根据合同ID和租户code获取应用授权情况
             */
            return function (params) {
                var deferred = $q.defer();
                $http.get('/orgapi/index.php?r=mtp/myscrm-organization/get-application-auth-info', {params: params})
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });
                return deferred.promise;
            }
        }])
        .service('getRenewalList', ['$http', '$q', function ($http, $q) {
            /**
             * 项目跟应用的关系（续签中哪些应用可以授权，哪些不能授权）
             */
            return function (params) {
                var deferred = $q.defer();
                util.myAjax({
                    url: '/orgapi/index.php?r=mtp/myscrm-organization/project-application-relation',
                    data: params,
                    type: 'POST',
                    success: function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    },
                    error: function () {
                        deferred.reject();
                    }

                });
                return deferred.promise;
            }
        }])
        .service('saveRenewal', ['$http', function ($http) {
            /**
             * 保存续签项目
             */
            return function (params = {}) {
                return $http.post('/orgapi/index.php?r=mtp/myscrm-organization/save-binding-auth', _.merge(params, {USE_FORM_DATA: false}));
            }

        }])
        .service('checkBusinessData', ['$http', function ($http) {

            return function (params = {}) {
                return $http.post('/orgapi/index.php?r=mtp/myscrm-organization/check-business-data', _.merge(params, {USE_FORM_DATA: false}));
            }

        }])
        .service('getContractApplicationInfo', ['$http', '$q', function ($http, $q) {
            /**
             * 指定合同的授权绑定情况
             */
            return function (params) {
                var deferred = $q.defer();
                $http.get('/orgapi/index.php?r=mtp/myscrm-organization/get-application-to-project-to-authorizes', {params: params})
                    .success(function (res) {
                        if (res.retCode == 0) {
                            deferred.resolve(res.data);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });
                return deferred.promise;
            }
        }])
        .service('apiService', ['$http', '$q', function ($http, $q) {
            var apis = {
                getRDSDataInstanceList: {
                    method: 'get',
                    api: '/orgapi/index.php?r=mtp/myscrm-organization/get-rds-database-instance-list'
                },
                updateOrganizationState: {
                    method: 'get',
                    api: '/orgapi/index.php?r=mtp/myscrm-organization/update-organization-state'
                },
                resetPwd: {method: 'post', api: '/orgapi/index.php?r=mtp/myscrm-organization/reset-pwd'},
                addSmsQuota: {method: 'post', api: '/orgapi/index.php?r=mtp/myscrm-organization/add-sms-quota'},
                deleteOrganization: {
                    method: 'post',
                    api: '/orgapi/index.php?r=mtp/myscrm-organization/delete-organization'
                },
                createOrganization: {
                    method: 'post',
                    api: '/orgapi/index.php?r=mtp/myscrm-organization/create-organization'
                },
                editOrganization: {
                    method: 'post',
                    api: '/orgapi/index.php?r=mtp/myscrm-organization/edit-org'
                },
                beforeAddSmsQuota: {
                    method: 'post',
                    api: '/orgapi/index.php?r=mtp/myscrm-organization/create-organization'
                },
                updateAll400Pwd: {
                    method: 'post',
                    api: '/orgapi/index.php?r=mtp/myscrm-organization/update-all-400-pwd'
                },
                getSmsQuota: {method: 'get', api: '/orgapi/index.php?r=mtp/myscrm-organization/get-sms-quota'},
                getAreaList: {method: 'get', api: '/api/index.php?r=contract/get-contract-area-list'},
                getProjects: {
                    method: 'get',
                    api: '/orgapi/index.php?r=mtp/myscrm-organization/get-project-auth-contract-list'
                },
                changeDisable: {
                    method: 'post',
                    api: '/orgapi/index.php?r=mtp/myscrm-organization/change-disable'
                },
                getNewestReason: {
                    method: 'get',
                    api: '/orgapi/index.php?r=mtp/myscrm-organization/get-newest-reason'
                },
                getListByProjectIdApplicationCode: {
                    method: 'get',
                    api: '/orgapi/index.php?r=mtp/myscrm-organization/get-list-by-project-id-application-code'
                },
                getOrgList: {
                    method: 'get',
                    api: G_CONFIG['api_prefix'] + 'user-auth/get-org-list'
                },
                getLdapUserList: {
                    method: 'get',
                    api: G_CONFIG['api_prefix'] + 'user-auth/get-ldap-user-list'
                },
                getAllBindAccounts: {
                    method: 'get',
                    api: G_CONFIG['api_prefix'] + 'maintainer-account/get-all-bind-accounts'
                },
                batchBindAccount: {
                    method: 'post',
                    api: G_CONFIG['api_prefix'] + 'maintainer-account/batch-bind-account'
                },
                setBq: {
                    method: 'post',
                    api: G_CONFIG['orgapi_prefix'] + 'mtp/myscrm-organization/set-bq'
                },
                unsetBq: {
                    method: 'post',
                    api: G_CONFIG['orgapi_prefix'] + 'mtp/myscrm-organization/unset-bq'
                },
                changeTenantType: {
                    method: 'post',
                    api: G_CONFIG['orgapi_prefix'] + 'mtp/myscrm-organization/update-test-org'
                },
                getAuthorizeProducts: {
                    method: 'get',
                    api: G_CONFIG['orgapi_prefix'] + 'api-gate/get-authorize-product-list'
                },
                createAuthorize: {
                    method: 'get',
                    api: G_CONFIG['orgapi_prefix'] + 'api-gate/create-authorize'
                },
                deleteAuthorize: {
                    method: 'get',
                    api: G_CONFIG['orgapi_prefix'] + 'api-gate/delete-authorize'
                },
                getAppKeyAndSecret: {
                    method: 'get',
                    api: G_CONFIG['orgapi_prefix'] + 'api-gate/get-app-key-and-secret'
                },
                resetAppSecret: {
                    method: 'get',
                    api: G_CONFIG['orgapi_prefix'] + 'api-gate/reset-app-secret'
                },
                copyLogging: {
                    method: 'get',
                    api: G_CONFIG['orgapi_prefix'] + 'api-gate/copy-app-secret'
                },
                removeAuthorize: {
                    method: 'post',
                    api: G_CONFIG['orgapi_prefix'] + 'mtp/myscrm-organization/delete-contract'
                },
                contractSearch: {
                    method: 'get',
                    api: '/api/index.php?r=contract/search'
                },
            };
            return function (params) {
                var deferred = $q.defer();
                $http[apis[params.name].method](apis[params.name].api, apis[params.name].method == 'get' ? {params: params.params} : params.params)
                    .success(function (res) {
                        if (+res.retCode === 0) {
                            deferred.resolve(res.data || res.result);
                        } else {
                            deferred.reject(res.retMsg);
                        }
                    })
                    .error(function () {
                        deferred.reject();
                    });
                return deferred.promise;
            }
        }])
        .controller('tenantCtl', [
            '$q',
            '$scope',
            '$filter',
            'appservice',
            'orgs',
            'contracts',
            'cancelContract',
            'updateDeliver',
            'editContract',
            'allPackages',
            'packagesByOrg',
            'contractRenewal',
            'getContractNum',
            'getRenewalApplication',
            'getRenewalList',
            'getContractApplicationInfo',
            'saveRenewal',
            'checkBusinessData',
            'apiService',
            'searchErpFields',
            function ($q, $scope, $filter, appservice, orgs, contracts, cancelContract, updateDeliver, editContract, allPackages, packagesByOrg, contractRenewal, getContractNum, getRenewalApplication, getRenewalList, getContractApplicationInfo, saveRenewal, checkBusinessData, apiService, searchErpFields) {

                appservice.name = '明源云客-租户管理';

                $scope.setAside = function (tenant, contract, sucCallback) {
                    util.confirm('确定作废吗？', {
                        ok: function () {
                            cancelContract({orgname: tenant.UniqueName, contract_id: contract.ContractId})
                                .then(function () {
                                    contract.Status = 2;
                                    ui.showSucTip('作废成功');

                                    sucCallback && sucCallback();
                                });
                        }
                    });
                };

                $scope.editContract = function (contract, dialog, dialogScope, organizationId) {
                    var packages = contract.packages;

                    var pkg;
                    for (var i = 0; pkg = packages[i]; i++) {
                        pkg.package_id = pkg.id;
                    }
                    return editContract({
                        contract_id: contract.ContractId,
                        contract_num: contract.ContractNum,
                        party_a: contract.PartyA,
                        contract_type: contract.ContractType,
                        begin_on: contract.BeginOn,
                        end_on: contract.EndOn,
                        area_id: contract.area_id,
                        organization_id: organizationId,
                        auth_info: packages,
                        establish_time: contract.establish_time,
                        authType: contract.authType,
                        category: contract.category,
                        promiseFulfilTime: contract.promiseFulfilTime,
                        actualFulfilTime: contract.actualFulfilTime,
                        promiseFulfilPrinciple: contract.promiseFulfilPrinciple,
                        promiseFulfilPrincipleName: contract.promiseFulfilPrincipleName
                    })
                        .then(function () {
                            dialog.close();

                            ui.showSucTip();
                        });
                };

                //编辑授权
                $scope.showEditTenant = function (item, dialog, dialogScope) {


                    $scope.curTenant = item;

                    dialogScope.setAside = function (contract) {
                        $scope.setAside(item, contract, function () {
                            getTenantInfo();
                        });
                    };

                    dialogScope.removeAuthorize = function (contract) {
                        util.confirm('确定要删除吗？', {
                            ok: function () {
                                apiService({
                                    name: 'removeAuthorize',
                                    params: {
                                        orgname: item.UniqueName,
                                        contract_id: contract.ContractId
                                    }
                                })
                                    .then(() => {
                                        getTenantInfo();
                                        ui.showSucTip('删除成功');
                                    })
                            }
                        });
                    };

                    //续租判断
                    dialogScope.showRenewal = function (item) {
                        /**
                         * ContractType 1:新增  2:增购
                         * 类型为新增时候不显示续租按钮
                         *
                         * 合同类型为增购,且在合同期内,并且不为作废状态,显示
                         *
                         *
                         * EndOn
                         * 合同结束时间
                         */
                        if (item.ContractType == 1) return false;

                        var dayEnd = new Date(item.EndOn),
                            now = new Date();

                        return dayEnd > now;


                    };

                    //展示已绑项目按钮
                    dialogScope.areadyBingProjNum = function (packages) {
                        var total = 0;
                        if (packages.length > 0) {
                            $.each(packages, function () {
                                total += this.used_num;
                            })
                        }

                        return total;

                    };


                    //显示续租弹窗
                    dialogScope.showEditRenewal = function (projInfo, renewalDialog, renewalDialogScope) {

                        renewalDialogScope.nextStep = false;
                        renewalDialogScope.renewalItems = [];

                        setTimeout(function () {
                            renewalDialog.reset();
                        }, 0);


                        //上一步
                        renewalDialogScope.prevRenewal = function () {
                            renewalDialogScope.nextStep = false;
                        };


                        //关闭弹窗
                        renewalDialogScope.closeRenewal = function () {
                            renewalDialog.close();
                        };


                        //初期展示续签列表
                        contractRenewal({orgname: item.UniqueName}).then(function (data) {
                            renewalDialogScope.renewalItems = data;

                        });


                        // 点击续签次数，可以查看续签的历史信息（合同号、租期），倒序排列，最新的在上面。
                        renewalDialogScope.showRenewCount = (item) => {

                            const div = record => `<div>合同号: ${ record.ContractCode }<br/></div>
                            <div>租期: ${ moment(record.BeginOn).format('YYYY-MM-DD') } 至 ${ moment(record.EndOn).format('YYYY-MM-DD') }</div>`;

                            return (item.RenewRecords || []).map(div).join('<br/>');

                        };

                        //搜索显示
                        renewalDialogScope.renewalExecute = function () {
                            contractRenewal({orgname: item.UniqueName, keyword: this.keyword}).then(function (data) {
                                renewalDialogScope.renewalItems = data;

                            })
                        };

                        //勾选续签列表
                        renewalDialogScope.projClick = function (item) {
                            return item.Selected = !item.Selected;
                        };
                        renewalDialogScope.toggleObjSelection = function ($event) {
                            $event.stopPropagation();
                        };


                        //全选框
                        renewalDialogScope.checkAll = function () {
                            if (!renewalDialogScope.selectedAll) {
                                renewalDialogScope.selectedAll = true;
                            } else {
                                renewalDialogScope.selectedAll = false;
                            }

                            angular.forEach(renewalDialogScope.renewalItems, function (item) {
                                item.Selected = renewalDialogScope.selectedAll;
                            });

                        };


                        //监听需要续签项目勾选框
                        renewalDialogScope.$watch("renewalItems", function (n, o) {
                            var trues = $filter("filter")(n, {Selected: true});
                            renewalDialogScope.flag = trues.length;
                        }, true);


                        //进入下一步授权
                        renewalDialogScope.nextRenewal = function () {


                            //检查是否勾选续签项目
                            if (renewalDialogScope.flag == 0) {
                                util.alert('请勾选需要续签项目!');
                                return false;
                            }

                            renewalDialogScope.nextStep = true;

                            renewalDialogScope.applicationInfo = [];


                            // 字段解释: CanNotUse == 1 授权是正常的, 不能再授权
                            // 非正常授权 且 有可用的授权数 才能选择
                            renewalDialogScope.canCheck = (app, selected) => {

                                return +app.CanNotUse === 0
                                    && _.some(
                                        renewalDialogScope.applicationInfo,
                                        x => x.UniqueName === app.UniqueName
                                            && x.IsQdAdvanced === app.IsQdAdvanced
                                            && (x.Num > 0 || (selected === undefined && +x.Num === 0 && !app.selected)))

                            };

                            renewalDialogScope.disableCheck = (app) => app.CanNotUse == '1';

                            //1\ 获取合同编号;
                            renewalDialogScope.contractNum = projInfo.ContractNum;


                            //2\ 传送contractId 获取 绑定应用列表
                            getRenewalApplication({
                                orgname: item.UniqueName,
                                contract_id: projInfo.ContractId
                            })
                                .then(function (data) {

                                    renewalDialogScope.applicationInfo = data;

                                })
                                .then(() => {

                                    getRenewalList({
                                        orgname: item.UniqueName,
                                        projects: _(renewalDialogScope.renewalItems).filter('Selected').map('ProjectId').value()
                                    }).then(function (data) {

                                        renewalDialogScope.renewalProjects = data;

                                        renewalDialogScope.renewalProjectsRaw = _.cloneDeep(data);

                                        _(renewalDialogScope.renewalItems).filter('Selected').each(x => {

                                            const findReApp = () => {

                                                const project = _.find(data, project => project.ProjectId == x.ProjectId);
                                                return _.find((project || {}).Apps, app => app.UniqueName == x.AppCode && app.IsQdAdvanced === x.IsQdAdvanced);

                                            };

                                            renewalDialogScope.updateSelection(findReApp(), true);

                                        });

                                    });
                                });

                            renewalDialogScope.updateSelection = function (reApp = {}, selected) {

                                // false => -1 true => 1;
                                const bool2Unit = bool => Math.round(Math.sin(+bool - 0.5) * 2);

                                const toggle = (app) => {
                                    app.selected = !app.selected;
                                    return app.selected;
                                };

                                const app = _.find(renewalDialogScope.applicationInfo, x => x.UniqueName === reApp.UniqueName && x.IsQdAdvanced === reApp.IsQdAdvanced);

                                if (app && renewalDialogScope.canCheck(reApp, selected)) {

                                    reApp.AuthorizeId = app.AuthorizeId;

                                    app.Num += -bool2Unit(selected === undefined ? reApp.selected : toggle(reApp));

                                } else {

                                    //!reApp.selected && toggle(reApp);
                                    if (!selected) {
                                        toggle(reApp);
                                    }

                                }

                            };


                        };


                        //确定勾选提交
                        renewalDialogScope.confirmRenewal = function () {

                            const auth = (xs) => {

                                return _(xs).map(x => _.map(_.filter(x.Apps, 'selected'), app => {

                                    return {
                                        ProjectId: x['ProjectId'],
                                        ApplicationCode: app['UniqueName'],
                                        AuthorizeId: app['AuthorizeId']
                                    };

                                })).flatten().value();

                            };

                            let auths = [];

                            const raw = auth(renewalDialogScope.renewalProjectsRaw);

                            const modified = auth(renewalDialogScope.renewalProjects);

                            const concat = (xs, ys, type) => auths = _.concat(auths, _.filter(xs, x => {

                                if (!_.some(ys, y => _.isEqual(x, y))) {
                                    x['type'] = type;
                                    return true;
                                } else {
                                    return false;
                                }


                            }));

                            concat(raw, modified, 'delete');
                            concat(modified, raw, 'add');

                            if (auths.length) {
                                saveRenewal({
                                    orgname: item.UniqueName,
                                    auth: auths
                                }).then(function (result) {

                                    util.alert('保存成功');
                                    renewalDialog.close();

                                    $scope.showEditTenant(item, dialog, dialogScope);

                                })
                            } else {
                                util.alert('请添加授权');
                            }

                        };

                        return false;
                    };


                    //查看合同已绑定项目
                    dialogScope.showAuthorizedProj = function (contract, authDialog, authDialogScope) {

                        authDialogScope.data.contractNum = contract.ContractNum;

                        setTimeout(function () {
                            authDialog.reset();
                        }, 0);

                        getContractApplicationInfo({
                            orgname: item.UniqueName,
                            contract_id: contract.ContractId
                        }).then(function (data) {
                            authDialogScope.data.authApplications = data;
                        });

                        //勾选应用
                        var authAppIdArr = [],
                            authAppArr = [];

                        authDialogScope.authAppClick = function ($event, app, projectId) {
                            var checkbox = $event.target,
                                action = (checkbox.checked ? 'add' : 'remove'),
                                indx = authAppIdArr.indexOf(projectId + app.AuthorizeId);

                            if (action == 'remove' && indx == -1) {
                                app['ProjectId'] = projectId;
                                app['ApplicationCode'] = app['AppCode'];
                                app['type'] = 'delete';
                                authAppIdArr.push(projectId + app.AuthorizeId);
                                authAppArr.push(app);
                            }

                            if (action == 'add' && indx != -1) {

                                authAppIdArr.splice(indx, 1);

                                authAppArr.splice(indx, 1);
                            }


                            authDialogScope.data.authAppArr = authAppArr;

                        }


                    };


                    //保存合同已绑定项目
                    dialogScope.editAuthorizedProj = function (data, authDialog, authDialogScope) {

                        if (data.authAppArr.length > 0) {

                            const renewal = (isForce) =>
                                saveRenewal({
                                    orgname: item.UniqueName,
                                    auth: data.authAppArr,
                                    isForce
                                }).then((result) => {

                                    authDialog.close();

                                    ui.showSucTip('修改成功');

                                    $scope.showEditTenant(item, dialog, dialogScope);

                                });

                            checkBusinessData({
                                orgname: item.UniqueName,
                                auth: data.authAppArr
                            })
                                .then((rsp) => {

                                rsp = _.get(rsp, 'data.data');

                                const groupByProjectName = _.groupBy(rsp, 'project_name');
                                const tips = _.map(groupByProjectName, (project, projectName) => `${projectName}${_.map(project, 'app_name').join('、')}有业务数据，至少要保留一个有效的授权`)
                                    .join('、');

                                if (tips) {
                                    util.confirm(tips, {
                                        ok: () => renewal(1)
                                    });
                                } else {
                                    renewal(0);
                                }

                            })
                        }

                        return false;

                    };


                    dialogScope.editContract = function (contract, innerDialog, innerDialogScope) {
                        $scope.editContract(contract, innerDialog, innerDialogScope, item.Id).then(function () {
                            getTenantInfo();
                        });

                        return false;
                    };

                    var categoryList = [
                        {name: '合同未归档', value: '1'},
                        {name: '款项未回', value: '2'},
                        {name: '合同未归档且款项未回', value: '3'},
                        {name: '结算款未支付', value: '4'},
                        {name: '合同扫描件未提供', value: '5'},
                        {name: '合同扫描件未提供且结算款未支付', value: '6'},
                    ];

                    //
                    const getMainProductApplications = ($dialogScope, uniqueName, contractCode, tenantData, $dialog, contractType = '') => {
                        allPackages({}, `&orgCode=${uniqueName}&contractCode=${contractCode}&contractType=${contractType}`).then(function (data) {
                            for (var key in data) {
                                if (data.hasOwnProperty(key)) {
                                    data[key].total_num = 0;
                                }
                            }

                            // $dialogScope.data.ContractType = tenantData.contracts.length > 0 ? 2 : 1;

                            $dialogScope.data.authType = '1';

                            $dialogScope.data.packages = data;

                            setTimeout(function () {
                                $dialog.reset();
                            }, 0);
                        });
                    };

                    const ddlConfigContractNum = ($dialogScope, uniqueName, contractCode, tenantData, $dialog, isCreation) => {


                        $dialogScope.isCreation = isCreation;
                        $dialogScope.contractTypeDisabled = true;

                        if (!$dialogScope.isCreation) {
                            apiService({
                                name: 'contractSearch',
                                params: {
                                    keyword: $dialogScope.data.ContractNum
                                }
                            })
                                .then(rs => {
                                    $dialogScope.contractTypeDisabled = _.some(_.map(rs, 'contract_code'), x => x === $dialogScope.data.ContractNum);
                                })
                        }

                        $dialogScope.ddlConfigContractNum = {
                            ajax: {
                                url: "/api/index.php?r=contract/search",
                                dataType: 'json',
                                delay: 250,
                                data: function (term, page) {
                                    $dialogScope.data.ContractNum = term;
                                    return {
                                        keyword: term,
                                        limit: 10
                                    };
                                },
                                results: function (data, page) {

                                    const found = _.some(data.data, x => x.contract_code === $dialogScope.data.ContractNum);

                                    if (!found) {
                                        data.data = _.concat({
                                            contract_code: $dialogScope.data.ContractNum,
                                            contract_id: -1
                                        }, data.data)
                                    }

                                    return {
                                        results: _.map(data.data, x => {
                                            x.text = x.contract_code;
                                            x.id = x.contract_id;
                                            return x;
                                        })
                                    };
                                },
                                cache: true
                            },
                            escapeMarkup: function (markup) {
                                return markup;
                            },
                            minimumInputLength: 1,
                            templateResult: function (data) {
                                return data;
                            },
                            templateSelection: function (data) {
                                return data;
                            },
                            onchange2: function (newVal) {
                                $dialogScope.data.ContractNum = newVal.contract_code ? newVal.contract_code : $dialogScope.data.ContractNum;
                                $dialogScope.data.PartyA = newVal.customer_full_name;
                                if (isCreation) {
                                    getMainProductApplications($dialogScope, uniqueName, $dialogScope.data.ContractNum, tenantData, $dialog, $dialogScope.data.ContractType);
                                }
                            }
                        }

                    };

                    //新增
                    dialogScope.onBeforeShowCreateContract = function (tenantData, $dialog, $dialogScope) {
                        dialogScope.onBeforeShowEditContract(tenantData, $dialog, $dialogScope, true);
                        $dialogScope.categoryList = categoryList;
                        $dialogScope.ddlConfigPrinciple = {
                            ajax: {
                                url: "/api/index.php?r=/erp-interface/get-users",
                                dataType: 'json',
                                delay: 250,
                                data: function (term, page) {
                                    return {
                                        keyword: term,
                                        limit: 10
                                    };
                                },
                                results: function (data, page) {
                                    return {
                                        results: data.data
                                    };
                                },
                                cache: true
                            },
                            escapeMarkup: function (markup) {
                                return markup;
                            },
                            minimumInputLength: 1,
                            templateResult: function (data) {
                                return data;
                            },
                            templateSelection: function (data) {
                                return data;
                            },
                            onchange2: function (newVal) {
                                $dialogScope.data.promiseFulfilPrinciple = newVal.id;
                            }
                        };

                        ddlConfigContractNum($dialogScope, item['UniqueName'], null, tenantData, $dialog, true);

                    };

                    // 修改
                    dialogScope.onBeforeShowEditContract = function (tenantData, $dialog, $dialogScope, isCreation) {

                        $dialogScope.$watch('data.ContractType', (newValue, oldValue) => {

                            if (isCreation) {

                                const _getMainProductApplications = _.debounce(() => {
                                    getMainProductApplications($dialogScope, item['UniqueName'], $dialogScope.data.ContractNum,
                                        tenantData, $dialog, newValue);
                                }, 10);

                                _getMainProductApplications();
                            }

                        });

                        ui.loading('', '正在加载…');
                        apiService({
                            name: 'getAreaList'
                        }).then(function (res) {
                            var items = res;
                            var tabData = [];
                            var item;
                            for (var i = 0; item = items[i]; i++) {
                                tabData.push({
                                    value: item.areaId + '',
                                    name: item.areaName
                                });
                            }
                            $dialogScope.items = tabData;
                        });
                        $dialogScope.categoryList = categoryList;
                        $dialogScope.data.area_id = tenantData.AreaId;
                        $dialogScope.autoAddEndDate = function () {
                            if ($dialogScope.data.BeginOn) {
                                $dialogScope.data.EndOn = moment($dialogScope.data.BeginOn).add('year', 1).format('YYYY-MM-DD');
                            }
                        };
                        if (!$dialogScope.data.EstablishTime) {
                            $dialogScope.data.establish_time = moment(GET_SERVER_TIME()).format('YYYY-MM-DD');
                        } else {
                            $dialogScope.data.establish_time = moment($dialogScope.data.EstablishTime).format('YYYY-MM-DD');
                        }

                        $dialogScope.ddlConfigPrinciple = {
                            ajax: {
                                url: "/api/index.php?r=/erp-interface/get-users",
                                dataType: 'json',
                                delay: 250,
                                data: function (term, page) {
                                    return {
                                        keyword: term,
                                        limit: 10
                                    };
                                },
                                results: function (data, page) {
                                    return {
                                        results: data.data
                                    };
                                },
                                cache: true
                            },
                            escapeMarkup: function (markup) {
                                return markup;
                            },
                            minimumInputLength: 1,
                            templateResult: function (data) {
                                return data;
                            },
                            templateSelection: function (data) {
                                return data;
                            },
                            onchange2: function (newVal) {
                                $dialogScope.data.promiseFulfilPrinciple = newVal.id;
                            }
                        };

                        ddlConfigContractNum($dialogScope);

                        setTimeout(function () {
                            if ($('#promiseFulfilPrinciple').length) {
                                $('#promiseFulfilPrinciple').data('select2').updateSelection({text: $dialogScope.data.promiseFulfilPrincipleName || ''});
                            }
                            if ($('#promiseContractNum').length) {
                                $('#promiseContractNum').data('select2').updateSelection({text: $dialogScope.data.ContractNum || ''});
                            }
                        }, 0)

                    };


                    dialogScope.createContract = function (contract, $dialog, $dialogScope) {
                        $scope.editContract(contract, $dialog, $dialogScope, item.Id).then(function () {
                            getTenantInfo();
                        });

                        return false;
                    };

                    dialogScope.beforeDisableProject = function ($dialog, $dialogScope) {

                        // 抽成Provider
                        $dialogScope.Page = {
                            query: {
                                orgCode: item.UniqueName,
                                status: 0,
                                projName: ''
                            },
                            checkAll: false,
                            searchErpFields: searchErpFields,
                            items: [],
                            pagination: {
                                params: {
                                    pageIndex: 1,
                                    pageSize: 10
                                },
                                total: 0,
                                change: function (pageIndex) {
                                    var thiz = $dialogScope.Page;
                                    thiz.pagination.params.pageIndex = pageIndex;
                                    thiz.search();
                                }
                            },
                            impl: {
                                filterSearchResult: function (res) {
                                    var thiz = $dialogScope.Page;
                                    thiz.items = res.data;
                                    thiz.pagination.total = res.total;
                                    thiz.checkAll = false;
                                }
                            },
                            getItems: function () {
                                return this.items;
                            },
                            setItems: function (items) {
                                this.items = items;
                                return this.getItems();
                            },
                            search: function (pageIndex) {
                                var thiz = this;
                                pageIndex && (thiz.pagination.params.pageIndex = pageIndex);
                                apiService({
                                    name: 'getProjects',
                                    params: thiz.getQuery()
                                }).then(function (res) {
                                    thiz.impl.filterSearchResult(res);
                                    thiz.updateCheckAll(false);
                                });
                            },
                            getQuery: function () {
                                return angular.extend({}, this.query, this.pagination.params);
                            },
                            check() {

                                const everyChecked = _.every(this.getItems(), 'checked');
                                const someUnchecked = _.some(this.getItems(), x => !x.checked);

                                if (everyChecked) {
                                    this.checkAll = everyChecked;
                                }

                                if (someUnchecked) {
                                    this.checkAll = !someUnchecked;
                                }


                            },
                            hasChecked() {

                                return _.some(this.getItems(), 'checked');

                            },
                            getDisabled(items) {

                                return _.chain(items || this.getItems())
                                    .filter('checked')
                                    .filter('is_disable')
                                    .value();

                            },
                            getEnabled(items) {

                                return _.chain(items || this.getItems())
                                    .filter('checked')
                                    .filter(x => x['is_disable'] === 0)
                                    .value();

                            },
                            updateCheckAll(value) {
                                // 有值赋值
                                if (value !== undefined) {
                                    this.checkAll = value;
                                }
                                _.map(this.getItems(), x => x.checked = this.checkAll);
                            },
                            init: function () {
                                $dialogScope.$on('onPage.query.status', function ($event, newValue, oldValue) {
                                    if (newValue != oldValue) {
                                        $dialogScope.Page.search(1);
                                    }
                                });
                                this.search();
                            }
                        };

                        $dialogScope.Page.init();

                        $dialogScope.beforeCancelDisableReason = function (project, $data, $dialog, $dialogScope) {

                            $dialogScope.today = moment(GET_SERVER_TIME()).format('YYYY-MM-DD');

                            //批量取消禁用 不调用
                            if (project && !_.isArray(project)) {
                                apiService({
                                    name: 'getNewestReason',
                                    params: {
                                        orgCode: item.UniqueName,
                                        p_projectId: project.ProjId,
                                        application_code: project.applicationCode
                                    }
                                }).then(function (res) {
                                    $dialogScope.reason = res.reason;
                                    $data.disable_type = res.disable_type;
                                    $data.disable_again_time = res.disable_again_time;
                                });
                            }


                        };

                        $dialogScope.beforeDisableReason = function (project, $data, $dialog, $dialogScope) {
                            $data.disable_type = '3';
                        };


                        $dialogScope.beforeDisableReasonDetail = function (project, $data, $dialog, $dialogScope) {

                            $dialogScope.disableType = {
                                1: '项目售罄',
                                2: '应用不好',
                                3: '其他'
                            };

                            apiService({
                                name: 'getListByProjectIdApplicationCode',
                                params: {
                                    orgCode: item.UniqueName,
                                    p_projectId: project.ProjId,
                                    application_code: project.applicationCode
                                }
                            }).then(function (res) {
                                if (res.length === 0) {
                                    ui.showErrTip('无禁用记录');
                                } else {
                                    $dialog.showModal();
                                    $dialogScope.data.items = _.map(res, x => {

                                        if (x.disable_again_time) {
                                            x.disable_again_time = moment(x.disable_again_time).format('YYYY-MM-DD')
                                        }

                                        return x;
                                    });
                                }
                            });

                            return false;
                        };

                        $dialogScope.disabled = function ($data, projects) {

                            if (!_.isArray(projects)) {
                                projects = [projects];
                            }

                            const _projects = $dialogScope.Page.getEnabled(projects);

                            if (_projects.length) {
                                projects = _projects;
                            }

                            const items = _.map(projects, project => ({
                                orgCode: item.UniqueName,
                                type: '1',
                                p_projectId: project.ProjId,
                                reason: $data.reason,
                                end_on: project.contractEndOn,
                                disable_type: $data.disable_type,
                                application_code: project.applicationCode
                            }));

                            apiService({
                                name: 'changeDisable',
                                params: {
                                    items,
                                    USE_FORM_DATA: false
                                }
                            }).then(function (res) {
                                if (res) {

                                    _.each(projects, project => {
                                        project.is_disable = 1;
                                        project.disable_time = moment(GET_SERVER_TIME()).format('YYYY-MM-DD');
                                        //status设置为已禁用
                                        project.status = '4';
                                    });

                                    ui.showSucTip('禁用成功');
                                } else {

                                    _.each(projects, project => {
                                        project.is_disable = 0;
                                    });
                                    ui.showErrTip('禁用失败');

                                }
                            });
                        };

                        $dialogScope.cancelDisabled = function ($data, projects) {

                            if (!_.isArray(projects)) {
                                projects = [projects];
                            }

                            const _projects = $dialogScope.Page.getDisabled(projects);

                            if (_projects.length) {
                                projects = _projects;
                            }

                            $data.disable_type = 3;

                            const items = _.map(projects, project => ({
                                orgCode: item.UniqueName,
                                type: '0',
                                p_projectId: project.ProjId,
                                reason: $data.reason,
                                end_on: project.contractEndOn,
                                disable_type: $data.disable_type,
                                application_code: project.applicationCode,
                                disable_again_time: $data.disable_again_time
                            }));

                            apiService({
                                name: 'changeDisable',
                                params: {
                                    items,
                                    USE_FORM_DATA: false
                                }
                            }).then(function (res) {
                                if (res) {

                                    console.log(res);

                                    _.each(projects, project => {
                                        project.is_disable = 0;
                                        project.disable_time = '';
                                        const found = _.find(res, {
                                            p_projectId: project.ProjId,
                                            application_code: project.applicationCode
                                        });
                                        if (found) {
                                            project.status = found.status;
                                        }
                                    });

                                    ui.showSucTip('取消禁用成功');
                                } else {
                                    _.each(projects, project => {
                                        project.is_disable = 0;
                                    });
                                    ui.showSucTip('取消禁用失败');
                                }
                            });
                        }

                    };

                    //查看绑定
                    let url = '/orgapi/index.php?r=mtp/myscrm-organization/get-project-bind-record-by-contract-id-application-code';
                    dialogScope.showBindRecord = (brData, brDialog, brDialogScope, options) => {
                        brDialogScope.pageIndex = 1;
                        brDialogScope.pageSize = 10;
                        brDialogScope.bindRecordPageChange = ($pageIndex, $pageSize) => {
                            brDialogScope.pageIndex = $pageIndex;
                            brDialogScope.pageSize = $pageSize;
                            getBindRecordDataList();
                        };
                        brDialogScope.keyword = '';

                        brDialogScope.bindRecordSearchFn = () => {
                            brDialogScope.pageIndex = 1;
                            brDialogScope.keyword = brDialogScope.bindRecordSearchKeyword;
                            getBindRecordDataList();
                        };

                        getBindRecordDataList();

                        function getBindRecordDataList() {
                            let params = {
                                orgname: item.UniqueName,
                                contractId: options.data.ContractId,
                                applicationCode: options.unique_name,
                                pageIndex: brDialogScope.pageIndex,
                                pageSize: brDialogScope.pageSize,
                                keyword: brDialogScope.keyword
                            };
                            if (options.IsQdAdvanced) {
                                params.IsQdAdvanced = options.IsQdAdvanced;
                            }

                            util.myAjax({
                                url: url,
                                data: params,
                                type: 'GET',
                                success: function (res) {
                                    if (res.retCode == 0) {
                                        brDialogScope.$apply(() => {
                                            brDialogScope.dataList = res.data.data;
                                            brDialogScope.total = res.data.total;
                                            setTimeout(() => {
                                                brDialogScope.resetDialog();
                                            }, 0);
                                        });
                                    } else {
                                        util.alert('系统错误')
                                    }
                                },
                                error: function () {
                                    util.alert('系统错误')
                                }
                            });
                        }
                    };

                    function getTenantInfo() {
                        contracts({orgname: item.UniqueName})
                            .then(function (data) {

                                    dialogScope.data = data;

                                }
                            );

                        packagesByOrg({orgname: item.UniqueName}).then(function (data) {
                            var clolors = ['#FDCF3A', '#E3645B', '#68B1E6', '#31B610', '#FAA103', '#950FAF', '#023FBB'];//黄，红，天空蓝，深绿，橙色，紫色，藏蓝

                            var seriesTotalData = [], seriesUsedData = [], seriesUnUsedData = [];

                            var authorizeTotal = 0;
                            var authorizeUsed = 0;
                            var authorizeUsable = 0;

                            var i = 0;
                            for (var key in data) {
                                if (data.hasOwnProperty(key)) {
                                    var item = data[key];

                                    var totalNum = item.total_num;
                                    var usedNum = item.used_num;
                                    var unUsedNum = totalNum - usedNum;

                                    authorizeTotal += totalNum;
                                    authorizeUsed += usedNum;
                                    authorizeUsable += unUsedNum;

                                    i++;
                                }
                            }

                            var i = 0;
                            for (var key in data) {
                                if (data.hasOwnProperty(key)) {
                                    var item = data[key];
                                    var totalNum = item.total_num;
                                    var usedNum = item.used_num;
                                    var unUsedNum = totalNum - usedNum;

                                    var name = key;

                                    var colorIndex = i % clolors.length;

                                    // 授权
                                    seriesTotalData.push({
                                        name: name + '　' + totalNum,
                                        color: clolors[colorIndex],
                                        y: getPercent(totalNum, authorizeTotal)
                                    });

                                    // 绑定
                                    seriesUsedData.push({
                                        name: name + '　' + usedNum,
                                        color: clolors[colorIndex],
                                        y: getPercent(usedNum, authorizeUsed)
                                    });

                                    // 可用
                                    seriesUnUsedData.push({
                                        name: name + '　' + unUsedNum,
                                        color: clolors[colorIndex],
                                        y: getPercent(unUsedNum, authorizeUsable)
                                    });

                                    i++;
                                }
                            }

                            $('#js_authorize_total').highcharts(getChartData(seriesTotalData, authorizeTotal));
                            $('#js_authorize_used').highcharts(getChartData(seriesUsedData, authorizeUsed));
                            $('#js_authorize_usable').highcharts(getChartData(seriesUnUsedData, authorizeUsable));
                        });
                    };

                    getTenantInfo();
                };


                // 计算两个整数的百分比值
                function getPercent(num, total) {
                    return total <= 0 ? 0 : (Math.round(num / total * 10000) / 100.00);
                }

                function getChartData(data, title) {
                    return {
                        chart: {
                            plotBackgroundColor: null,
                            plotBorderWidth: null,
                            plotShadow: false,
                            spacing: [0, 0, 0, -100],
                            height: 100,
                            width: 280
                        },
                        title: {
                            text: title,
                            align: 'center',
                            verticalAlign: 'middle',
                            floating: true,
                            style: {"fontSize": "20px", 'font-weight': 'bold'},
                            y: 5
                        },
                        tooltip: {
                            pointFormat: '{series.name}: <b>{point.percentage:.2f}%</b>'
                        },
                        plotOptions: {
                            pie: {
                                allowPointSelect: true,
                                cursor: 'pointer',
                                dataLabels: {
                                    enabled: false
                                },
                                showInLegend: true,
                                point: {
                                    events: {
                                        legendItemClick: function () {
                                            return false;   // 目的是屏蔽点击隐藏 serie 的效果
                                        }
                                    }
                                }
                            }
                        },
                        legend: {
                            align: 'right',
                            verticalAlign: 'middle',
                            borderWidth: 0,
                            layout: 'vertical',
                            floating: true,
                            itemStyle: {color: "#333333", cursor: "", fontSize: "12px", fontWeight: "bold"} // 目的是屏蔽连接鼠标箭头
                        },
                        series: [{
                            name: '占比',
                            type: "pie",
                            innerSize: '80%',
                            data: data,
                            states: {
                                hover: {
                                    enabled: false
                                }
                            }
                        }]
                    };
                }

                $scope.showDeliver = (data, $dialog, $dialogScope) => {
                    //变更记录
                    util.myAjax({
                        url: '/orgapi/index.php?r=mtp/myscrm-organization/get-delivery-change-log',
                        data: {
                            organizationId: data.Id
                        },
                        type: 'GET',
                        success: function (res) {
                            if (res.retCode == 0) {
                                $dialogScope.$apply(() => {
                                    $dialogScope.historyList = res.data;
                                });
                            } else {
                                util.alert('系统错误')
                            }
                        },
                        error: function () {
                            util.alert('系统错误')
                        }
                    });
                    //自动补全
                    $('.edit-delivery-info-username').autoComplete({
                        url: '/api/index.php?r=erp-interface/get-users',
                        select: function (vals) {
                            $dialogScope.$apply(() => {
                                $dialogScope.data[vals.type] = vals.name;
                                $dialogScope.data[vals.type + 'Phone'] = vals.phone.replace(/^(\+86)/g, '');
                                $dialogScope.data[vals.type + 'Email'] = vals.email;
                                $dialogScope.data[vals.type + 'GUID'] = vals.guid
                            });
                        }
                    });
                };

                $scope.saveDeliver = function (data, dialog, dialogScope) {
                    updateDeliver({
                        orgname: data.UniqueName,
                        deliver: data.Deliver,
                        deliver_guid: data.DeliverGUID,
                        deliver_phone: data.DeliverPhone,
                        deliver_email: data.DeliverEmail,
                        custom_manager: data.CustomManager,
                        custom_manager_phone: data.CustomManagerPhone,
                        custom_manager_email: data.CustomManagerEmail,
                        custom_manager_guid: data.CustomManagerGUID,
                        area: data.Area
                    }).then(function (res) {
                        var index = util.indexOf(data, $scope.list, function (a, b) {
                            return a.Id === b.Id;
                        });

                        if (index > -1) {
                            $scope.list[index] = data;
                        }

                        dialog.close();
                        ui.showSucTip();
                    });

                    return false;
                };


                function showResult(res, msg, howLong, timeout = 0) {
                    setTimeout(() => {
                        if (res) {
                            ui.showSucTip(msg + '成功', howLong);
                        } else {
                            ui.showErrTip(msg + '失败');
                        }
                    }, timeout);
                }

                // 新增租户
                $scope.createOrganization = function ($data) {
                    apiService({
                        name: 'createOrganization',
                        params: {
                            orderCode: $data.orderCode,
                            friendlyName: $data.friendlyName,
                            uniqueName: $data.uniqueName,
                            email: $data.email,
                            instanceId: $data.instanceId,
                            isTest: $data.isTest,
                            CstGuid: $data.CstGuid,
                            TopCstName: $data.TopCstName
                        }
                    }).then(function (res) {
                        $scope.query.execute();
                        showResult(res, '新增租户');
                    });
                };
                // 获取 rds 列表
                $scope.getRDSDataInstanceList = function ($data, $dialogScope, tenant) {

                    // 租户类型
                    $dialogScope.tenantType = tenantType;
                    $data.isTest = '0';

                    if (tenant) {
                        $data.orderCode = tenant.orderCode;
                        $data.friendlyName = tenant.FriendlyName;
                        $data.uniqueName = tenant.UniqueName;
                        $data.email = tenant.Email;
                        $data.instanceId = tenant.InstanceId;
                        $data.CstGuid = tenant.Id;
                        $data.TopCstName = tenant.orderCode;

                        console.log(tenant);

                        $dialogScope.isEdit = true;
                    }

                    function formatCustomer(repo) {
                        if (repo.loading) return repo.text;

                        return repo.text;
                    }

                    function formatCustomerSelection(repo) {
                        return repo.text;
                    }

                    // 客户下拉框处理
                    $dialogScope.ddlConfigCustomer = {
                        allowClear: false,
                        placeholder: '顶级客户简称',
                        ajax: {
                            url: "/api/index.php?r=erp-interface/get-erp-customer-info",
                            dataType: 'json',
                            delay: 250,
                            data: function (term) {
                                return {
                                    keyword: term,
                                    limit: 10
                                };
                            },
                            results: function (json, page) {
                                var data = [];
                                if (json.retCode === "0") {
                                    data = json.data;
                                    $.each(data, function (i, d) {
                                        d.text = d.CstName + (d.Level ? '-' + d.Level : '');
                                        d.id = d.CSTGUID;
                                    });
                                }
                                return {
                                    results: data
                                };
                            },
                            cache: true
                        },
                        escapeMarkup: function (markup) {
                            return markup;
                        },
                        minimumInputLength: 1,
                        onchange2: function (newVal) {
                            $data.TopCstName = newVal.DjCstName;
                            $data.CstGuid = newVal.CSTGUID;
                        },
                        formatResult: formatCustomer,
                        formatSelection: formatCustomerSelection // omitted for brevity, see the source of this page
                    };

                    apiService({
                        name: 'getRDSDataInstanceList'
                    }).then(function (res) {
                        $data.rdsList = res;
                    });

                };

                // 获取 rds 列表
                $scope.boforeEditTenant = function ($data, $dialogScope, tenant) {

                    // 租户类型
                    $dialogScope.tenantType = tenantType;

                    if (tenant) {
                        $data.orderCode = tenant.orderCode;
                        $data.friendlyName = tenant.FriendlyName;
                        $data.uniqueName = tenant.UniqueName;
                        $data.email = tenant.Email;
                        $data.instanceId = tenant.InstanceId;
                        $data.CstGuid = tenant.Id;
                        $data.TopCstName = tenant.AliasName;
                        $data.isTest = tenant.isTest;
                    }

                };

                $scope.editOrganization = ($data) => {

                    const params = {
                        id: $data.CstGuid,
                        org_name: $data.friendlyName,
                        org_alias: $data.TopCstName,
                        is_test: $data.isTest
                    };

                    apiService({
                        name: 'editOrganization',
                        params
                    }).then(function (res) {
                        $scope.query.execute();
                        showResult(res, '编辑租户');
                    });

                };

                // fix
                $scope.selectRds = function ($data, id) {
                    $data.instanceId = id;
                    $data.showRdsTable = false;
                };

                // 修改密码
                $scope.passwd = function ($data) {
                    apiService({
                        name: 'updateAll400Pwd',
                        params: {
                            pwd: $data.pwd1
                        }
                    }).then(function (res) {
                        showResult(res, '修改密码');
                    });
                };


                // 启用/禁用/删除 init
                $scope.beforeEnabledDisabled = function ($data, text) {
                    $data.stateText = text;
                };

                // 启用/禁用
                $scope.enabledDisabled = function ($data, id, state) {
                    apiService({
                        name: 'updateOrganizationState',
                        params: {
                            organizationId: id,
                            state: state,
                            reason: $data.reason
                        }
                    }).then(function (res) {
                        $scope.query.execute();
                        showResult(res, state == 0 ? '启用租户' : '禁用租户');
                    });
                };

                // 删除
                $scope.deleteOrganization = function ($data, id) {
                    apiService({
                        name: 'deleteOrganization',
                        params: {
                            organizationId: id,
                            reason: $data.reason
                        }
                    }).then(function (res) {
                        $scope.query.execute();
                        showResult(res, '删除租户');
                    });
                };

                // 重置密码
                $scope.resetPwd = function ($data, id) {
                    apiService({
                        name: 'resetPwd',
                        params: {
                            organizationId: id,
                            pwd: $data.pwd1,
                            email: $data.Email
                        }
                    }).then(function (res) {
                        showResult(res, '重置密码');
                    });
                };

                // 赠送短信
                $scope.addSmsQuota = function ($data, id) {
                    apiService({
                        name: 'addSmsQuota',
                        params: {
                            organizationId: id,
                            addQuota: $data.addQuota,
                            amount: $data.amount
                        }
                    }).then(function (res) {
                        showResult(res, '赠送短信');
                    });
                };

                // 更改租户类型
                $scope.changeTenantType = function ($data, item) {
                    apiService({
                        name: 'changeTenantType',
                        params: {
                            orgCode: item.UniqueName,
                            updateType: item.isTest == '1' ? 'remove' : 'add'
                        }
                    }).then(function (res) {

                        item.isTest == '1' ? item.isTest = '0' : item.isTest = '1';

                        showResult(res, `设置为${item.isTest == '1' ? '正式' : '测试'}租户`);

                    });
                };


                $scope.beforeSetApiGate = (tenant, $dialogScope, $data) => {

                    import('../../../../tenant/dialog/css/set_api_gate.css');

                    const org_code = tenant['UniqueName'];

                    $dialogScope.openProducts = [];

                    $dialogScope.createAuthorize = (group_ids) => apiService({
                        name: 'createAuthorize',
                        params: {
                            org_code,
                            group_ids
                        }
                    }).then(res => {
                        showResult(res, '添加授权', 1000, 500);
                    });

                    $dialogScope.deleteAuthorize = (group_ids) => apiService({
                        name: 'deleteAuthorize',
                        params: {
                            org_code,
                            group_ids
                        }
                    }).then(res => {
                        showResult(res, '删除授权', 1000, 500);
                    });

                    $dialogScope.getAuthorizeProducts = () => apiService({
                        name: 'getAuthorizeProducts',
                        params: {
                            org_code,
                            app_name: tenant['app_names'].join(',')
                        }
                    }).then(res => {
                        _.each(res, x => {
                            x['text'] = x['group_name'];
                            x['checked'] = x['is_authorize'];
                        });
                        $dialogScope.openProducts = _.filter(res, 'checked');
                        $dialogScope.products = res;
                    });


                    $dialogScope.getAppKeyAndSecret = () => {

                        if (_.filter($dialogScope.products, x => +x.is_authorize === 1).length) {
                            return apiService({
                                name: 'getAppKeyAndSecret',
                                params: {
                                    org_code
                                }
                            }).then(res => {
                                if (res) {
                                    $dialogScope.appKey = res['app_key'];
                                    $dialogScope.appSecret = res['app_secret'];
                                    $dialogScope.content = `AppSecret: ${$dialogScope.appSecret}, \nAppKey: ${$dialogScope.appKey}`;
                                    tenant['api_gate_is_authorize'] = 1;
                                    $scope.$applyAsync();
                                }
                                return res;
                            });
                        }

                        return Promise.resolve();

                    };

                    $dialogScope.resetAppSecret = () => apiService({
                        name: 'resetAppSecret',
                        params: {
                            org_code
                        }
                    })
                        .then(() => $dialogScope.getAppKeyAndSecret())
                        .then(res => {
                            showResult(res, '重置AppSecret', 1000, 500);
                        });

                    $dialogScope.copyLogging = () => apiService({
                        name: 'copyLogging',
                        params: {
                            org_code
                        }
                    });

                    $dialogScope.showAfterCopy = () => setTimeout(() => ui.showSucTip('复制AppSecret成功', 1000), 500)


                    $dialogScope.getAuthorizeProducts()
                        .then(() => {

                            const overlay = method => {
                                const $container = $('.ui-dialog-content.container-padding');
                                if (method === 'on') {
                                    $container.on('click', e => {
                                        e.preventDefault();
                                        e.stopPropagation();
                                    });
                                    $dialogScope.isDisabled = true;
                                    $dialogScope.$applyAsync();
                                } else {
                                    $dialogScope.isDisabled = false;
                                    $container.off('click');
                                }
                            };

                            $dialogScope.$watch('openProducts', (newValue, oldValue) => {

                                if (newValue !== oldValue) {

                                    const addProduct = _.differenceBy(newValue, oldValue, _.property('text'));
                                    const deleteProduct = _.differenceBy(oldValue, newValue, _.property('text'));

                                    let promise = Promise.resolve();

                                    if ($dialogScope.isDisabled) {
                                        return;
                                    }

                                    overlay('on');

                                    if (addProduct.length) {
                                        promise = promise.then(() => $dialogScope.createAuthorize(addProduct[0]['group_id']))
                                            .then(() => $dialogScope.getAuthorizeProducts());
                                    }

                                    if (deleteProduct.length) {
                                        promise = promise.then(() => $dialogScope.deleteAuthorize(deleteProduct[0]['group_id']))
                                            .then(() => $dialogScope.getAuthorizeProducts());
                                    }

                                    if (deleteProduct.length && !newValue.length) {
                                        $dialogScope.appSecret = '';
                                        $dialogScope.appKey = '';
                                        $dialogScope.content = '';
                                        tenant['api_gate_is_authorize'] = 0;
                                        $scope.$applyAsync();
                                    }

                                    if (!$dialogScope.appKey) {
                                        promise = promise.then(() => $dialogScope.getAppKeyAndSecret());
                                    }

                                    promise.then(() => overlay('off'));

                                }
                            });
                        })
                        .then(() => $dialogScope.getAppKeyAndSecret());

                };

                // beforeAddSmsQuota
                $scope.beforeAddSmsQuota = function ($data, id) {
                    apiService({
                        name: 'getSmsQuota',
                        params: {
                            organizationId: id
                        }
                    }).then(function (res) {
                        angular.extend($data, res);
                    });
                };

                $scope.isBq = 0;

                $scope.$watch('isBq', (newValue, oldValue) => {

                    if (newValue != oldValue) {
                        $scope.query.execute();
                    }

                });

                $scope.tenantType = [{
                    text: '全部',
                    value: ''
                }].concat(tenantType);

                $scope.tenantStatus = [{
                    text: '全部',
                    value: ''
                }].concat(tenantStatus);

                $scope.query = {
                    page: 1,
                    pageSize: 10,
                    keyword: '',
                    total: 100,
                    isTest: '',
                    orgStatus: '',
                    execute: function (page) {
                        var query = $scope.query;

                        query.page = page || query.page;

                        const params = {
                            page: query.page,
                            pageSize: query.pageSize,
                            keyword: query.keyword,
                            isTest: query.isTest,
                            orgStatus: query.orgStatus
                        };

                        if (+$scope.isBq == 1) {
                            params.isBq = 1;
                        }

                        return orgs(params)
                            .then(function (data) {
                                data = data || {items: [], total: 0};

                                query.total = data.total;
                                $scope.list = data.items;
                            });
                    }
                };


                /**
                 * 管理400账号
                 */
                $scope.relateRoleTemplateUrl = require('../../../../tenant/dialog/relate_role.html');


                /**
                 * 管理400账号
                 * @param $dialogScope
                 */
                $scope.beforeShowManagerAcount = function ($dialogScope) {

                    $dialogScope.currentOrg = null;

                    $dialogScope.selected = {
                        data: [],
                        add: function (users) {

                            if (!_.isArray(users)) {
                                users = [users];
                            }

                            this.data = users.concat(this.data);

                            this.data = _.chain(this.data)
                                .flatten()
                                .uniq(false, _.property('UserGUID'))
                                .value();

                        },
                        remove: function (users) {

                            if (!_.isArray(users)) {
                                users = [users];
                            }

                            this.data = _.filter(this.data, x => _.every(users, user => user['UserGUID'] != x['UserGUID']));

                        }
                    };

                    $dialogScope.toggleSelect = function (user) {

                        user.checked = !user.checked;

                        if (!!user.checked) {
                            this.selected.add(user);
                        } else {
                            this.selected.remove(user);
                        }

                    };

                    $dialogScope.localSearch = () => {

                        const {keyword, userList} = $dialogScope;

                        _(userList).map(user => {

                            if (user['UserName'].includes(keyword)
                                || user['UserCode'].includes(keyword)) {
                                user['hidden'] = false;
                            } else {
                                user['hidden'] = true;
                            }

                            return user;

                        })

                    };

                    $dialogScope.orgTreeConfig = {
                        transformData: function (data) {
                            let org;
                            for (var i = 0; i < data.length; i++) {
                                org = data[i];
                                org.name = org['BUName'];
                                org.id = org['BUGUID'];
                                if (org.son && org.son.length) {
                                    org.children = this.transformData(org.son);
                                }
                            }
                            return data;
                        },
                        treeClick: function (e) {

                            $dialogScope.currentOrg = e.node;

                            if ($dialogScope.currentOrg) {
                                apiService(
                                    {
                                        name: 'getLdapUserList',
                                        params: {
                                            buGUID: $dialogScope.currentOrg.id
                                        }
                                    }
                                ).then(res => {

                                    $dialogScope.userList = _.map(res['userList'], user => {
                                        user.checked = _.some($dialogScope.selected.data, x => user['UserGUID'] == x['UserGUID']);
                                        return user;
                                    });

                                })
                            }

                        }
                    };

                    // 组织列表
                    apiService(
                        {
                            name: 'getOrgList'
                        }
                    ).then(res => $dialogScope.orgList = res['orgList']);

                    // 已选用户
                    apiService(
                        {
                            name: 'getAllBindAccounts'
                        }
                    ).then(res => {

                        _.map(res, x => {

                            x.UserGUID = x.user_id;
                            x.UserName = x.username;
                            x.UserCode = x.user_code;
                            x.checked = true;

                            return x;

                        });

                        $dialogScope.selected.add(res);

                    })

                };

                $scope.saveManagerAcount = function ($dialogScope) {

                    const showTip = res => res ? ui.showSucTip('保存成功') : ui.showErrTip('保存失败');

                    let selectedData = $dialogScope.selected.data;

                    selectedData = _.map(selectedData, x => {

                        x['userguid'] = x.UserGUID;
                        x['usercode'] = x.UserCode;
                        x['username'] = x.UserName;

                        return _.pick(x, 'userguid', 'usercode', 'username');
                    });

                    apiService(
                        {
                            name: 'batchBindAccount',
                            params: selectedData
                        }
                    ).then(showTip)

                };

                $scope.setBq = (item) => {

                    const showTip = res => res ? ui.showSucTip('设置成功') : ui.showErrTip('设置失败');

                    apiService(
                        {
                            name: 'setBq',
                            params: {
                                orgId: item.Id
                            }
                        }
                    ).then(showTip)
                        .then($scope.query.execute)

                };

                $scope.unsetBq = (item) => {

                    const showTip = res => res ? ui.showSucTip('设置成功') : ui.showErrTip('设置失败');

                    apiService(
                        {
                            name: 'unsetBq',
                            params: {
                                orgId: item.Id
                            }
                        }
                    ).then(showTip)
                        .then($scope.query.execute)

                };

                $scope.query.execute();
            }])
});
